package com.example.spring.redis.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.example.spring.redis.common.model.UserModel;
import com.example.spring.redis.service.UserManagerService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户管理类
 * </p>
 *
 * @author Ashe
 * @version V1.0.0
 * @date 2019/12/27 0027$ 11:36$
 * @modificationHistory=========================逻辑或功能性重大变更记录
 * @modify By: {修改人} 2019/12/27 0027$
 * @modify reason: {方法名}:{原因}
 * ...
 * @since V1.0.0
 */
@Service
@Slf4j
public class UserManagerServiceImpl implements UserManagerService {
    /**
     * 模拟数据库
     */
    public static final List<UserModel> userNameList = Lists.newArrayList();

    @Override
    public int add(String groupName,String userName) {
        userNameList.add(UserModel.builder().groupName(groupName).name(userName).build());
        return userNameList.size();
    }

    @Cacheable(value = "globalCache", cacheManager = "simpleCacheManager", key = "#groupName")
    @Override
    public List<UserModel> findByGroupName(String groupName) {
        return findByNamePrivate(groupName);
    }

    @CacheEvict(value = "globalCache", cacheManager = "simpleCacheManager", key = "#groupName")
    @Override
    public void reloadByGroupName(String groupName) {
        log.info("UserRestController clear cache with key:" + groupName);
    }

    private List<UserModel> findByNamePrivate(String groupName) {
        log.info("UserRestController find by db");
        if (StringUtils.isEmpty(groupName)) {
            return userNameList;
        }
        return userNameList.stream().filter(p -> StringUtils.equals(p.getGroupName(), groupName)).collect(Collectors.toList());
    }
}

